import React, { useState, useEffect, useCallback } from 'react';
import { Input } from 'antd'
import { openPageSelect } from '@inbiz/basic/PageSelect'
import { InbizIcon, getNowPageRoute } from '@inbiz/utils'
import { getMessage } from '@inbiz/react';

/** 内置页面选择及外部地址输入 **/
const PageInput = (props: {
  value?: string;
  disabled?: boolean;
  onChange?: (value: string) => void;
  defaultValue?: string | null | undefined;
  notSelectNowPage?: boolean | undefined;
  range?: "all" | undefined;
  client?: "web" | "wap" | undefined;
}) => {
  const { value, disabled, onChange, ...other } = props
  // 页面显示文本(页面名/链接地址)
  const [text, $text] = useState<string>('')

  // 同步更新页面显示文本
  useEffect(() => {
    initValue(value)
  }, [value])

  // 集计算显示文本
  const initValue = (value?: string) => {
    if (value && typeof value === 'string' && value !== '') {
      if (value.includes('[outside]')) {
        // 外链
        $text(value.replace('[outside]', ''));
      } else {
        let arr = value.split(',');
        if (other.range === 'all') {
          let [v1, v2, v3, v4, v5, v6] = arr;
          if (v1 && v2 && v3 && v4 && v5 && v6) {
            if (other.notSelectNowPage && v5 === getNowPageRoute()) {
              $text('');
              onChange?.('')
              return
            }
            $text(v6);
          } else {
            // 外链地址
            $text(value.replace('[outside]', ''));
          }
        } else {
          if (arr[0] && arr[1] && arr[2]) {
            if (other.notSelectNowPage && arr[0] === getNowPageRoute()) {
              $text('');
              onChange?.('')
              return
            }
            $text(arr[2]);
          } else {
            // 外链地址
            $text(value.replace('[outside]', ''));
          }
        }
      }
    } else {
      $text('');
    }
  }

  // 打开弹窗选择内置页面
  const open = useCallback(() => {
    openPageSelect(other).then((res: string) => {
      initValue(res)
      onChange?.(res)
    })
  }, [])

  return (
    <Input
      value={text}
      disabled={disabled}
      placeholder={getMessage('ProcessManage.edit_page_placeholder')}
      onChange={(e: any) => { $text(e.target.value); onChange?.(`${e.target.value?.trim() !== '' ? '[outside]' : ''}${e.target.value}`) }}
      suffix={
        <InbizIcon
          type='icon-ic-arrow-down-bold'
          onClick={open}
          style={{
            color: 'rgba(0,0,0,.25)',
            transform: 'scaleX(.85) scaleY(1.2)'
          }}
        />
      }
    />
  )
}

export default React.memo(PageInput, (prevProps: any, nextProps: any) => {
  return prevProps.value === nextProps.value;
})